{% extends 'base.html' %}
{% load static %}

{% block title %}发布帖子 - 本地有约{% endblock %}

{% block content %}
<div class="container py-4">
    <div class="row justify-content-center">
        <div class="col-lg-8">
            <div class="card border-0 shadow">
                <div class="card-header bg-primary text-white">
                    <h4 class="mb-0"><i class="fas fa-edit me-2"></i>发布新帖子</h4>
                </div>
                <div class="card-body p-4">
                    <form id="createPostForm">
                        {% csrf_token %}

                        <!-- 帖子标题 -->
                        <div class="mb-4">
                            <label for="postTitle" class="form-label fw-bold">帖子标题</label>
                            <input type="text" class="form-control form-control-lg" id="postTitle" name="title"
                                   placeholder="请输入吸引人的标题..." required maxlength="200">
                            <div class="form-text">好的标题能吸引更多读者</div>
                        </div>

                        <!-- 帖子类型和活动 -->
                        <div class="row mb-4">
                            <div class="col-md-6">
                                <label for="postType" class="form-label fw-bold">帖子类型</label>
                                <select class="form-select" id="postType" name="post_type">
                                    <option value="discussion">💬 讨论</option>
                                    <option value="experience">📚 经验分享</option>
                                    <option value="question">❓ 提问</option>
                                    <option value="announcement">📢 公告</option>
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label for="postEvent" class="form-label fw-bold">关联活动（可选）</label>
                                <select class="form-select" id="postEvent" name="event_id">
                                    <option value="">不关联活动</option>
                                    {% for event in events %}
                                    <option value="{{ event.id }}">{{ event.title }}</option>
                                    {% endfor %}
                                </select>
                            </div>
                        </div>

                        <!-- 帖子内容 -->
                        <div class="mb-4">
                            <label for="postContent" class="form-label fw-bold">帖子内容</label>
                            <textarea class="form-control" id="postContent" name="content"
                                      rows="15" placeholder="详细描述您的内容... 支持 Markdown 语法" required></textarea>
                            <div class="form-text">
                                <i class="fas fa-info-circle me-1"></i>
                                支持 Markdown 语法，可以插入图片、链接等
                            </div>
                        </div>

                        <!-- 功能按钮 -->
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <button type="button" class="btn btn-outline-secondary" onclick="previewContent()">
                                    <i class="fas fa-eye me-2"></i>预览
                                </button>
                                <button type="button" class="btn btn-outline-secondary ms-2" onclick="saveDraft()">
                                    <i class="fas fa-save me-2"></i>存草稿
                                </button>
                            </div>
                            <div>
                                <button type="button" class="btn btn-secondary me-2" onclick="window.history.back()">
                                    <i class="fas fa-arrow-left me-2"></i>取消
                                </button>
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-paper-plane me-2"></i>发布帖子
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>

            <!-- 预览区域 -->
            <div id="previewArea" class="card mt-4 d-none">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-eye me-2"></i>内容预览</h5>
                </div>
                <div class="card-body" id="previewContent">
                    <!-- 预览内容将在这里显示 -->
                </div>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('createPostForm');
    const postContent = document.getElementById('postContent');

    // 自动保存草稿
    let autoSaveTimer;
    postContent.addEventListener('input', function() {
        clearTimeout(autoSaveTimer);
        autoSaveTimer = setTimeout(saveDraft, 2000);
    });

    // 加载草稿
    loadDraft();

    form.addEventListener('submit', async function(e) {
        e.preventDefault();

        const submitBtn = form.querySelector('button[type="submit"]');
        const originalText = submitBtn.innerHTML;

        // 显示加载状态
        submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>发布中...';
        submitBtn.disabled = true;

        const formData = new FormData(form);

        try {
            const response = await fetch('{% url "location:create_post" %}', {
                method: 'POST',
                body: formData,
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                }
            });

            const result = await response.json();

            if (result.status === 'success') {
                // 清除草稿
                localStorage.removeItem('postDraft');

                // 显示成功消息
                showAlert('帖子发布成功！', 'success');

                // 跳转到帖子详情页
                setTimeout(() => {
                    window.location.href = '{% url "location:post_detail" 0 %}'.replace('0', result.post_id);
                }, 1500);
            } else {
                showAlert('发布失败：' + result.message, 'error');
                submitBtn.innerHTML = originalText;
                submitBtn.disabled = false;
            }
        } catch (error) {
            showAlert('发布失败：网络错误', 'error');
            submitBtn.innerHTML = originalText;
            submitBtn.disabled = false;
            console.error('Error:', error);
        }
    });
});

function previewContent() {
    const content = document.getElementById('postContent').value;
    const previewArea = document.getElementById('previewArea');
    const previewContent = document.getElementById('previewContent');

    if (content.trim()) {
        // 简单的 Markdown 预览（实际项目中可以使用完整的 Markdown 解析器）
        let html = content
            .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
            .replace(/\*(.*?)\*/g, '<em>$1</em>')
            .replace(/\[(.*?)\]\((.*?)\)/g, '<a href="$2" target="_blank">$1</a>')
            .replace(/\n/g, '<br>');

        previewContent.innerHTML = html;
        previewArea.classList.remove('d-none');

        // 滚动到预览区域
        previewArea.scrollIntoView({ behavior: 'smooth' });
    } else {
        showAlert('请输入内容后再预览', 'warning');
    }
}

function saveDraft() {
    const title = document.getElementById('postTitle').value;
    const content = document.getElementById('postContent').value;
    const postType = document.getElementById('postType').value;
    const eventId = document.getElementById('postEvent').value;

    if (title || content) {
        const draft = {
            title: title,
            content: content,
            postType: postType,
            eventId: eventId,
            savedAt: new Date().toLocaleString()
        };

        localStorage.setItem('postDraft', JSON.stringify(draft));
        showAlert('草稿已自动保存', 'info');
    }
}

function loadDraft() {
    const draft = localStorage.getItem('postDraft');
    if (draft) {
        const data = JSON.parse(draft);

        if (confirm(`发现未保存的草稿（保存于 ${data.savedAt}），是否加载？`)) {
            document.getElementById('postTitle').value = data.title || '';
            document.getElementById('postContent').value = data.content || '';
            document.getElementById('postType').value = data.postType || 'discussion';
            document.getElementById('postEvent').value = data.eventId || '';

            showAlert('草稿已加载', 'success');
        }
    }
}

function showAlert(message, type) {
    // 移除现有的提示
    const existingAlert = document.querySelector('.custom-alert');
    if (existingAlert) {
        existingAlert.remove();
    }

    const alert = document.createElement('div');
    alert.className = `custom-alert alert alert-${type === 'error' ? 'danger' : type} alert-dismissible fade show`;
    alert.style.cssText = `
        position: fixed;
        top: 100px;
        right: 20px;
        z-index: 9999;
        min-width: 300px;
        box-shadow: 0 4px 12px rgba(0,0,0,0.15);
    `;
    alert.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;

    document.body.appendChild(alert);

    // 3秒后自动消失
    setTimeout(() => {
        if (alert.parentNode) {
            alert.remove();
        }
    }, 3000);
}
</script>

<style>
.form-control-lg {
    border-radius: 10px;
    border: 2px solid #e9ecef;
    padding: 1rem;
}

.form-control-lg:focus {
    border-color: #0d6efd;
    box-shadow: 0 0 0 0.2rem rgba(13, 110, 253, 0.1);
}

.card {
    border-radius: 15px;
}

.card-header {
    border-radius: 15px 15px 0 0 !important;
}

.btn {
    border-radius: 8px;
    padding: 0.5rem 1.5rem;
}
</style>
{% endblock %}